package com.wrb.pwd.service;

import com.alibaba.fastjson.JSONArray;
import com.wrb.pwd.constant.Constant;
import com.wrb.pwd.enums.PasswordTypeEnum;
import com.wrb.pwd.model.User;
import com.wrb.pwd.utils.PageUtils;
import com.wrb.pwd.utils.SecurityAES;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @author wrb
 * @date 2019/9/16 13:59
 */
public class UserService {

	private static List<User> userList;

	public static List<User> getUserList() {
		return userList;
	}

	static {
		userList = readJsonFile();
	}

	private UserService() {
	}

	public static UserService getInstance() {
		return Inner.INSTANCE;
	}

	private static class Inner {
		private static final UserService INSTANCE = new UserService();
	}

	/**
	 * 查看用户密码列表
	 *
	 * @return
	 */
	public PageUtils getUserList(String platform, int pageNo, int pageSize) {
		List<User> filterList = userList;
		if (platform != null && !"".equals(platform.trim())) {
			filterList = userList.stream().filter(p -> p.getPlatform() != null && p.getPlatform().contains(platform)).collect(Collectors.toList());
		}
		return PageUtils.startPage(pageNo, pageSize, filterList);
	}

	/**
	 * 新增一个用户信息
	 *
	 * @param user
	 * @return
	 */
	public boolean insertUser(User user) {
		try {
			userList.add(user);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 更新一个用户信息
	 *
	 * @param user
	 * @return
	 */
	public boolean updateUser(User user) {
		try {
			for (User filterUser : userList) {
				if (filterUser.getId().equals(user.getId())) {
					if (user.getName() != null && !"".equals(user.getName().trim())) {
						filterUser.setName(user.getName());
					}
					if (user.getEmail() != null && !"".equals(user.getEmail().trim())) {
						filterUser.setEmail(user.getEmail());
					}
					if (user.getPhone() != null && !"".equals(user.getPhone().trim())) {
						filterUser.setPhone(user.getPhone());
					}
					if (user.getAuxiliaryEmail() != null && !"".equals(user.getAuxiliaryEmail().trim())) {
						filterUser.setAuxiliaryEmail(user.getAuxiliaryEmail());
					}
					if (user.getUpdateTime() != null) {
						filterUser.setUpdateTime(user.getUpdateTime());
					}
					if (user.getRemark() != null && !"".equals(user.getRemark().trim())) {
						filterUser.setRemark(user.getRemark());
					}
					if (user.getPassword() != null && !"".equals(user.getPassword())) {
						filterUser.setPassword(user.getPassword());
						filterUser.setPasswordTypeList(user.getPasswordTypeList());
						filterUser.setPasswordLength(user.getPasswordLength());
						filterUser.setSeed(user.getSeed());
					}
					break;
				}
			}
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 通过 id 删除 user
	 *
	 * @param id
	 * @return
	 */
	public boolean deleteUser(String id) {
		try {
			userList = userList.stream().filter(p -> !id.equals(p.getId())).collect(Collectors.toList());
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 通过 id 获取 user
	 *
	 * @param id
	 * @return
	 */
	public User getUser(String id) {
		for (User user : userList) {
			if (user.getId().equals(id)) {
				return user;
			}
		}
		return null;
	}

	private static List<User> readJsonFile() {
		StringBuilder jsonStrs = new StringBuilder();
		BufferedReader reader = null;
		InputStream in = null;
		try {
			in = UserService.class.getResourceAsStream("/" + Constant.DATA_FILE_NAME);
			InputStreamReader inputStreamReader = new InputStreamReader(in, "UTF-8");
			reader = new BufferedReader(inputStreamReader);
			String tempStr = null;
			while ((tempStr = reader.readLine()) != null) {
				jsonStrs.append(tempStr);
			}
		} catch (IOException e) {
			e.printStackTrace();
			throw new IllegalArgumentException("处理json文件流错误");
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					throw new IllegalArgumentException("处理json文件流错误1");
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					throw new IllegalArgumentException("处理json文件流错误2");
				}
			}
		}
		String decrypt = jsonStrs.toString();
		if (!"".contentEquals(jsonStrs)) {
			// AES解密
			decrypt = SecurityAES.decrypt(jsonStrs.toString().trim());
		}

		assert decrypt != null;
		List<User> userList = JSONArray.parseArray(decrypt.trim(), User.class);
		if (userList == null || userList.isEmpty()) {
			userList = new ArrayList<>();
		}
		return userList;
	}

	/**
	 * 修改密码规则
	 *
	 * @param platformStr
	 * @param passwordLength 密码长度 最低4位 最高100位
	 * @return
	 */
	public String generatePassword(String platformStr, int passwordLength, int seed, List<PasswordTypeEnum> typeEnumList) {
		if (platformStr.length() < passwordLength) {
			platformStr += getRandomStr(passwordLength - platformStr.length(), seed);
		}

		StringBuilder passwordSB = new StringBuilder();
		//先把所有需要的密码类型加上
		int i = 0;
		for (; i < typeEnumList.size(); i++) {
			PasswordTypeEnum passwordTypeEnum = typeEnumList.get(i);
			passwordSB.append(PasswordTypeEnum.getCharByType(passwordTypeEnum, platformStr.charAt(i) + seed));
		}
		for (; i < passwordLength; i++) {
			int h = new Random(platformStr.charAt(i) + seed).nextInt(seed + 16385) % typeEnumList.size();
			PasswordTypeEnum passwordTypeEnum = typeEnumList.get(h);
			passwordSB.append(PasswordTypeEnum.getCharByType(passwordTypeEnum, platformStr.charAt(i) + seed));
		}
		return passwordSB.toString();
	}

	private static final String RANDOM_STR = "qwetyuiopasdfghjklzxcvbnm1234567890!@#$%^&*()_+{}|:<>?,./;'[]=/*-+`~";

	private String getRandomStr(int num, long seed) {
		StringBuilder sb = new StringBuilder();
		for (; num > 0; num--) {
			int random = new Random(seed + num * 10).nextInt(RANDOM_STR.length());
			sb.append(RANDOM_STR.charAt(random));
		}
		return sb.toString();
	}

}
